package com.hmdp.mq.order;/**
 * @Description: TODO
 * @Author: sats@jz
 * @Date: 2024/10/29 15:31
 **/

import cn.hutool.core.util.StrUtil;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.exception.VoucherException;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.impl.VoucherOrderServiceImpl;
import com.hmdp.service.impl.VoucherServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年10月29日 15:31
 */
@Component
@Slf4j
public class OrderSecMq {
    @Resource
    private VoucherOrderServiceImpl voucherOrderService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    // 绑定交换机、队列、路由键
    @RabbitListener( bindings = @QueueBinding(
            value = @Queue(value = "order.seckill.queue", durable = "true"),
            exchange = @Exchange(value = "order.exchange", type = "direct", durable = "true"),
            key = "order.seckill.routing.key"
    ))
    @Transactional
    public void createOrder(VoucherOrder voucherOrder){
        // 幂等判断
        VoucherOrder voucherOrder1 = voucherOrderService.getById(voucherOrder.getId());
        if (voucherOrder1 != null){
            log.info("mq, 订单已存在");
            return;
        }
        try{

            // 库存见一
            // 扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock",0) // 乐观锁，解决超卖
                    .update();
            if(!success){
                log.error("mq, 库存不足");
            }
            voucherOrderService.save(voucherOrder);
            log.info("mq, 扣减库存成功");

        }catch (Exception e){
            log.error("mq, 下单失败, 订单详情：", voucherOrder);
        }

    }
}
